﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using YJ.JobService.Jobs;
using YJ.Utilities.Json;
using YJ.Utilities.WindowsService;
using YJ.JobSchedule.Configuration;
using System.Reflection;
using System.Collections.Concurrent;
using System.Diagnostics;
using YJ.Utilities.AppDomainDynamic;

namespace YJ.JobService
{
    public partial class MainForm : Form
    {
        /// <summary>
        ///反射文件路径
        /// </summary>
        private readonly string jobsReflectionFileName = "jobconfig/yj.jobservice.reflection.joblist";
        /// <summary>
        /// windows服务文件路径
        /// </summary>
        private readonly string winserviceFileName = "jobconfig/yj.jobservice.winservice.joblist";

        public MainForm()
        {
            JobConfiguationManager.SetConfigFilePath("jobconfig/");
            InitializeComponent();
            //Control.CheckForIllegalCrossThreadCalls = false;
        }
        private ConcurrentDictionary<string, ReflectionJob> reflectionJobs;//所有的反射任务,key为JobKey
        private ConcurrentDictionary<string, WinServices> winservices;//所有的windows服务,key为ServiceName
        private ConcurrentDictionary<string, JobConfiguration> Configs = new ConcurrentDictionary<string, JobConfiguration>();

        #region 反射任务

        #region 基础方法
        /// <summary>
        /// 刷新所有的发射任务
        /// </summary>
        /// <param name="isFromFile">是否强制从配置文件中读取数据</param>
        /// <returns></returns>
        public async Task RefreshReflectionJobs(bool isFromFile = false)
        {
            if (File.Exists(jobsReflectionFileName))
            {
                try
                {
                    reflectionJobs = await JsonHelper.DeserializeFromFileAsync<ConcurrentDictionary<string, ReflectionJob>>(jobsReflectionFileName);

                }
                catch
                {
                    reflectionJobs = new ConcurrentDictionary<string, ReflectionJob>();
                }
            }
            else
            {
                reflectionJobs = new ConcurrentDictionary<string, ReflectionJob>();
            }

            foreach (var item in reflectionJobs.Keys)
            {

                JobConfiguration config;

                if (!Configs.ContainsKey(item) || isFromFile)
                {//如果字典中不存在,则新增

                    config = await JobConfiguationManager.GetJobConfigurationByKeyAsync(item);
                    if (config == null)
                        continue;

                    Configs.AddOrUpdate(item, config, (key, value) => { return config; });
                }
                //else
                //{
                //    //存在则在字典中获取
                //    bool b = Configs.TryGetValue(item, out config);
                //    if (!b || config == null)
                //        continue;
                //}

                //if (!config.IsDisabled && config.Schedule != null)
                //{//如果已启用切已配置调度,则启动任务
                //    StartReflectionJob(config.JobKey);
                //}
            }

            BindReflectionJobs();
        }

        /// <summary>
        /// 绑定反射任务到界面
        /// </summary>
        private void BindReflectionJobs()
        {

            var refjobs = Configs.Where(r => reflectionJobs.Keys.Contains(r.Key)).ToList();

            var result = refjobs.Select(
                 r =>
                 {
                     JobConfiguration job = r.Value;
                     dynamic d = new
                     {
                         JobKey = r.Key,
                         JobName = job.Name,
                         DisabledStatus = job.IsDisabled ? "已禁用" : "启用中",
                         RunningStatus = JobConfiguationManager.IsRunning(r.Key) ? "运行中.." : "未运行",
                         HasUnit = job.Schedule == null ? "未配置" : "已配置"
                     };
                     return d;
                 }).Where(r => r != null).ToList();

            dgvReflectionJobs.DataSource = result;
        }

        /// <summary>
        /// 添加一条反射任务
        /// </summary>
        /// <param name="job"></param>
        public async Task AddReflectionJobs(ReflectionJob job)
        {
            bool b = reflectionJobs.TryAdd(job.JobKey, job);
            if (!b)
            {
                MessageBox.Show(job.JobKey + ":任务添加失败,请重试!");
                return;
            }
            await SaveReflectionJobs();
            await RefreshReflectionJobs();
        }

        /// <summary>
        /// 禁用并停止反射任务
        /// </summary>
        /// <param name="jobKey"></param>
        /// <returns></returns>
        private async Task StopReflectionJob(string jobKey)
        {
            Configs[jobKey].IsDisabled = true;
            JobConfiguationManager.StopJob(jobKey);
            await JobConfiguationManager.SaveJobConfiguration(Configs[jobKey]);
        }

        /// <summary>
        /// 启动反射任务
        /// </summary>
        /// <param name="jobKey"></param>
        /// <returns></returns>
        private async Task StartReflectionJob(string jobKey)
        {
            var reflectionInfo = reflectionJobs[jobKey];

            JobConfiguration jobConfig;
            bool b = Configs.TryGetValue(jobKey, out jobConfig);
            if (!b || jobConfig == null || jobConfig.IsDisabled)
                return;

            if (reflectionJobs == null || jobConfig.Schedule == null)
                return;

            if (JobConfiguationManager.IsRunning(jobKey))
                return;

            JobConfiguationManager.StartJob(Configs[jobKey], () =>
            {
                Task.Run(() =>
                {
                    try
                    {
                        var d1 = DateTime.Now;
                        using (ProxyManager px = new ProxyManager(reflectionInfo.ApplicationDirectory))
                        {
                            px.Invoke(reflectionInfo.AssemblyPath, reflectionInfo.ClassNameSpace, reflectionInfo.MethodName);
                        }
                        /*
                        var ass = Assembly.LoadFrom(reflectionInfo.AssemblyPath);

                        Type type = ass.GetType(reflectionInfo.ClassNameSpace);

                        var method = type.GetMethod(reflectionInfo.MethodName);
                        if (method.IsStatic)
                            method.Invoke(null, null);
                        else
                        {
                            var obj = ass.CreateInstance(reflectionInfo.ClassNameSpace);
                            method.Invoke(obj, null);
                        }
                        */
                        var d2 = DateTime.Now;
                        Log4Logger.WriteInfo(string.Format("【{0}:{1}】任务执行完成,耗时:{2}秒!", jobKey, Configs[jobKey].Name, (d2 - d1).TotalMinutes.ToString("f2")));
                    }
                    catch (Exception ex)
                    {
                        Log4Logger.WriteError(string.Format("【{0}:{1}】任务执行发生错误!", jobKey, Configs[jobKey].Name), ex);
                    }
                });
            });
            await JobConfiguationManager.SaveJobConfiguration(Configs[jobKey]);
        }

        /// <summary>
        /// 保存反射任务
        /// </summary>
        /// <returns></returns>
        private async Task SaveReflectionJobs()
        {
            await JsonHelper.SerializeToFileAsync(this.reflectionJobs, jobsReflectionFileName);
        }
        #endregion

        #region 反射界面事件
        private void button1_Click(object sender, EventArgs e)
        {
            new AddReflectionJob(this).ShowDialog();
        }

        private async void dgvReflectionJobs_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var column = dgvReflectionJobs.Columns[e.ColumnIndex];

            if (e.RowIndex < 0)
                return;
            dynamic data = dgvReflectionJobs.Rows[e.RowIndex].DataBoundItem;
            if (data == null)
                return;
            string jobKey = data.JobKey;
            if (column.Name == "Config")
            {//配置               
                new ConfigForm(jobKey, this).ShowDialog();
            }
            else if (column.Name == "SetStop")
            {//停止

                JobConfiguration job;
                bool b = Configs.TryGetValue(jobKey, out job);

                if (b && job != null && !job.IsDisabled)
                {
                    job.IsDisabled = true;
                    Configs.AddOrUpdate(jobKey, job, (key, value) => { return job; });
                    await SaveJobConfiguration(job);
                    await RefreshReflectionJobs();
                    if (JobConfiguationManager.IsRunning(jobKey))
                        JobConfiguationManager.StopJob(jobKey);
                }
                else
                    return;
            }
            else if (column.Name == "SetEnabled")
            {//启用

                JobConfiguration job;
                bool b = Configs.TryGetValue(jobKey, out job);

                if (b && job != null && job.IsDisabled)
                {
                    job.IsDisabled = false;
                    Configs.AddOrUpdate(jobKey, job, (key, value) => { return job; });
                    await SaveJobConfiguration(job);
                    await RefreshReflectionJobs();
                }
                else
                    return;
            }
            else if (column.Name == "SetRun")
            {//运行

                JobConfiguration job;
                bool b = Configs.TryGetValue(jobKey, out job);
                if (!b || job == null)
                {
                    return;
                }
                if (job.Schedule == null)
                {
                    MessageBox.Show("请先配置执行计划!");
                    return;
                }
                if (JobConfiguationManager.IsRunning(jobKey))
                {
                    MessageBox.Show("任务正在运行中!");
                    return;
                }
                if (job.IsDisabled)
                {
                    MessageBox.Show("任务已禁用,请先启用!");
                    return;
                }
                await StartReflectionJob(jobKey);
                await RefreshReflectionJobs();
            }
            else if (column.Name == "JobName")
            {
                ReflectionJob job;
                bool b = reflectionJobs.TryGetValue(jobKey, out job);
                if (!b || job == null)
                {
                    return;
                }
                ShowDes(Control.MousePosition, job);
            }
            else if (column.Name == "Delete")
            {
                if (MessageBox.Show("真的要移除该任务吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    await JobConfiguationManager.RemoveJobAsync(jobKey);
                    JobConfiguration job;
                    ReflectionJob rjob;
                    reflectionJobs.TryRemove(jobKey, out rjob);
                    Configs.TryRemove(jobKey, out job);
                    await SaveReflectionJobs();
                    await RefreshReflectionJobs();
                }
            }
        }

        private async void brnRStartAll_Click(object sender, EventArgs e)
        {
            foreach (var item in reflectionJobs.Keys)
            {
                JobConfiguration job;
                if (Configs.TryGetValue(item, out job) && job != null)
                {
                    if (job.IsDisabled && job.Schedule != null)
                    {
                        job.IsDisabled = false;
                        Configs.TryUpdate(item, job, null);
                        await StartReflectionJob(item);
                        await SaveJobConfiguration(job);

                    }
                    else if (job.Schedule != null)
                    {
                        await StartReflectionJob(item);
                    }
                    else if (job.Schedule == null)
                    {
                        MessageBox.Show("任务:" + item + ",任务未配置执行计划");
                    }
                }
            }
            await RefreshReflectionJobs();
        }

        private async void btnRStopAll_Click(object sender, EventArgs e)
        {
            foreach (var item in reflectionJobs.Keys)
            {
                await StopReflectionJob(item);
            }
            await RefreshReflectionJobs();
        }

        private void dgvReflectionJobs_SelectionChanged(object sender, EventArgs e)
        {
            dgvReflectionJobs.ClearSelection();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            RefreshReflectionJobs(true);
        }

        #endregion

        #endregion

        #region windows服务

        #region 基础方法
        /// <summary>
        /// 刷新windows服务列表
        /// </summary>
        /// <returns></returns>
        public async Task RefreshWinservices(bool isFromFile = false)
        {
            if (File.Exists(winserviceFileName))
            {
                try
                {
                    winservices = await JsonHelper.DeserializeFromFileAsync<ConcurrentDictionary<string, WinServices>>(winserviceFileName);

                }
                catch
                {
                    winservices = new ConcurrentDictionary<string, WinServices>();
                }
            }
            else
            {
                winservices = new ConcurrentDictionary<string, WinServices>();
            }

            var jobKeys = winservices.SelectMany(r => r.Value.JobKeys).ToList();

            foreach (var item in jobKeys)
            {

                JobConfiguration config;

                if (!Configs.ContainsKey(item) || isFromFile)
                {//如果字典中不存在,则新增

                    config = await JobConfiguationManager.GetJobConfigurationByKeyAsync(item);
                    if (config == null)
                        continue;
                    Configs.AddOrUpdate(item, config, (key, value) => { return config; });
                }
            }

            await BindWinservices();
        }

        /// <summary>
        /// 刷新服务的任务列表
        /// </summary>
        /// <returns></returns>
        public async Task RefreshWinservicesJobs()
        {
            if (lsbWinservices.Items.Count == 0)
            {
                dgvWinserviceJobs.DataSource = null;
                return;
            };
            if (lsbWinservices.SelectedIndex < 0)
            {
                lsbWinservices.SelectedIndex = 0;
            }

            var serviceName = lsbWinservices.SelectedValue.ToString();
            await BindWinserviceJobs(serviceName);
        }

        /// <summary>
        /// 记录上一次选择的serviceName
        /// </summary>
        private string selectedServiceName = null;

        /// <summary>
        /// 绑定windows服务的List数据
        /// </summary>
        /// <returns></returns>
        public async Task BindWinservices()
        {
            var data = await Task.Run(() =>
               {
                   var result = winservices.Keys.Select(r =>
                    {
                        string status = "暂无";
                        try
                        {
                            if (!WinServiceHelper.IsExists(r))
                            {
                                status = "未安装";
                            }
                            else
                                status = ((winserviceStatus)WinServiceHelper.GetStatus(r)).ToString();
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.ToString());
                        }

                        return new
                        {
                            ServiceName = r,
                            Text = string.Format("{0}【{1}】", r, status)
                        };
                    }).ToList();
                   return result;
               });
            lsbWinservices.DataSource = data;
        }

        /// <summary>
        /// 绑定服务的任务DataGridView数据
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>

        public async Task BindWinserviceJobs(string serviceName)
        {
            var data = await Task.Run(() =>
                {
                    WinServices win;
                    if (!winservices.TryGetValue(serviceName, out win) || win == null)
                    {
                        return null;
                    }

                    var jobs = Configs.Where(r => win.JobKeys.Contains(r.Key)).ToList();

                    var result = jobs.Select(
                      r =>
                      {
                          JobConfiguration job = r.Value;
                          dynamic d = new
                          {
                              JobKey = r.Key,
                              JobName = job.Name,
                              DisabledStatus = job.IsDisabled ? "已禁用" : "启用中",
                              HasUnit = job.Schedule == null ? "未配置" : "已配置"
                          };
                          return d;
                      }).Where(r => r != null).ToList();

                    return result;
                });
            dgvWinserviceJobs.DataSource = data;
        }


        /// <summary>
        /// 添加一个windows服务
        /// </summary>
        /// <param name="win"></param>
        public async Task AddWinservice(WinServices win)
        {
            bool b = winservices.TryAdd(win.ServiceName, win);
            if (!b)
            {
                MessageBox.Show(win.ServiceName + ":服务添加失败,请重试!");
                return;
            }
            await SaveWinservice();
            await RefreshWinservices();
            await RefreshWinservicesJobs();
            Log4Logger.WriteInfo(win.ServiceName + ":windows服务已添加,包含了:" + win.JobKeys.Aggregate((x, y) => x + "," + y));
        }

        /// <summary>
        /// 保存所有的windows服务数据
        /// </summary>
        /// <returns></returns>
        public async Task SaveWinservice()
        {
            await JsonHelper.SerializeToFileAsync(this.winservices, winserviceFileName);
        }

        private enum winserviceStatus
        {
            未运行 = 1,
            正在启动 = 2,
            正在停止 = 3,
            正在运行 = 4,
            即将继续 = 5,
            即将暂停 = 6,
            已暂停 = 7
        }

        private async Task SetupService(string serviceName)
        {
            await Task.Run(() =>
            {
                WinServices win;
                if (!winservices.TryGetValue(serviceName, out win) || win == null)
                {
                    MessageBox.Show(serviceName + ":服务不存在!");
                    return;
                }
                if (WinServiceHelper.IsExists(serviceName))
                {
                    MessageBox.Show(serviceName + ":服务已经安装!");
                    return;
                }
                if (!File.Exists(win.ServiceExePath))
                {
                    MessageBox.Show(serviceName + ":服务安装路径【" + win.ServiceExePath + "】不存在!");
                    return;
                }
                try
                {
                    WinServiceHelper.Install(win.ServiceExePath);
                    WinServiceHelper.Start(serviceName);
                    WinServiceHelper.SetAuto(serviceName);
                    //MessageBox.Show(serviceName + ":服务安装且启动成功!");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    MessageBox.Show("安装失败,请重试!");
                }
            });
        }

        private async Task StartService(string serviceName)
        {
            await Task.Run(() =>
            {
                try
                {
                    WinServiceHelper.Start(serviceName);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    MessageBox.Show(serviceName + "启动失败,请重试!");
                }
            });
        }

        private async Task StopService(string serviceName)
        {
            await Task.Run(() =>
            {
                try
                {
                    WinServiceHelper.Stop(serviceName);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    MessageBox.Show(serviceName + "停止失败,请重试!");
                }
            });
        }

        private async Task RestartService(string serviceName)
        {
            await Task.Run(() =>
            {
                try
                {
                    WinServiceHelper.Restart(serviceName);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    MessageBox.Show(serviceName + "重启失败,请重试!");
                }
            });
        }

        private async Task RemoveService(string serviceName)
        {
            await Task.Run(() =>
            {
                try
                {
                    WinServiceHelper.UnInstall(serviceName);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
                WinServices win;
                if (!winservices.TryRemove(serviceName, out win) || win == null)
                {
                    MessageBox.Show(serviceName + "卸载服务失败,请重试!");
                    return;
                }
            });
        }

        #endregion

        #region windows服务界面事件响应
        private async void btnStartAllWinService_Click(object sender, EventArgs e)
        {
            Loading.ShowLoading();
            foreach (dynamic item in lsbWinservices.Items)
            {
                string name = item.ServiceName;
                await StartService(name);
            }

            await RefreshWinservices();
            await RefreshWinservicesJobs();
            Loading.CloseLoading();
        }

        private async void btnStopAllWinService_Click(object sender, EventArgs e)
        {
            Loading.ShowLoading();
            foreach (dynamic item in lsbWinservices.Items)
            {
                string name = item.ServiceName;
                await StopService(name);
            }

            await RefreshWinservices();
            await RefreshWinservicesJobs();
            Loading.CloseLoading();
        }

        private async void btnWStartAll_Click(object sender, EventArgs e)
        {
            var jobConfigs = Configs.Where(r => winservices.Values.SelectMany(q => q.JobKeys).Contains(r.Key)).ToList();
            if (!jobConfigs.Any())
                return;
            Loading.ShowLoading();
            foreach (var item in jobConfigs)
            {
                if (!item.Value.IsDisabled)
                    continue;
                var job = item.Value;
                job.IsDisabled = false;
                Configs.TryUpdate(item.Key, job, null);
                await SaveJobConfiguration(job);
            }
            await RefreshWinservices();
            await RefreshWinservicesJobs();
            Loading.CloseLoading();
        }

        private async void btnWStopAll_Click(object sender, EventArgs e)
        {
            Loading.ShowLoading();
            var jobConfigs = Configs.Where(r => winservices.Values.SelectMany(q => q.JobKeys).Contains(r.Key)).ToList();


            foreach (var item in jobConfigs)
            {
                if (!item.Value.IsDisabled)
                    continue;

                var job = item.Value;
                job.IsDisabled = true;
                Configs.TryUpdate(item.Key, job, null);
                await SaveJobConfiguration(job);
            }
            await RefreshWinservices();
            await RefreshWinservicesJobs();
            Loading.CloseLoading();
        }

        private async void lsbWinservices_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (lsbWinservices.Items.Count > 0 && lsbWinservices.SelectedIndex >= 0 && lsbWinservices.SelectedValue != null)
                {
                    selectedServiceName = lsbWinservices.SelectedValue.ToString();
                    await RefreshWinservicesJobs();
                }
                else
                    dgvWinserviceJobs.DataSource = null;

            }
            catch
            {
                selectedServiceName = null;
                dgvWinserviceJobs.DataSource = null;
            }

        }

        private async void dgvWinserviceJobs_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var column = dgvWinserviceJobs.Columns[e.ColumnIndex];

            if (e.RowIndex < 0)
                return;
            dynamic data = dgvWinserviceJobs.Rows[e.RowIndex].DataBoundItem;
            if (data == null)
                return;
            string jobKey = data.JobKey;
            if (column.Name == "ConfigW")
            {//配置               
                new ConfigForm(jobKey, this).ShowDialog();
            }
            else if (column.Name == "SetStopW")
            {//停止

                JobConfiguration job;
                bool b = Configs.TryGetValue(jobKey, out job);

                if (b && job != null && !job.IsDisabled)
                {
                    job.IsDisabled = true;
                    Configs.AddOrUpdate(jobKey, job, (key, value) => { return job; });
                    await SaveJobConfiguration(job);
                    await RefreshWinservicesJobs();
                }
                else
                    return;
            }
            else if (column.Name == "SetEnabledW")
            {//启用

                JobConfiguration job;
                bool b = Configs.TryGetValue(jobKey, out job);

                if (b && job != null && job.IsDisabled)
                {
                    job.IsDisabled = false;
                    Configs.AddOrUpdate(jobKey, job, (key, value) => { return job; });
                    await SaveJobConfiguration(job);
                    await RefreshWinservicesJobs();
                }
                else
                    return;
            }
            else if (column.Name == "JobNameW")
            {
                WinServices job;
                bool b = winservices.TryGetValue(jobKey, out job);
                if (!b || job == null)
                {
                    return;
                }
                ShowDes(Control.MousePosition, job);
            }

        }

        private async void 安装服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Loading.ShowLoading();
            await SetupService(lsbWinservices.SelectedValue.ToString());
            await RefreshWinservices();
            await RefreshWinservicesJobs();
            Loading.CloseLoading();
        }

        private async void 启动服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Loading.ShowLoading();
            await StartService(lsbWinservices.SelectedValue.ToString());
            await RefreshWinservices();
            await RefreshWinservicesJobs();
            Loading.CloseLoading();
        }

        private async void 停止服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Loading.ShowLoading();
            await StopService(lsbWinservices.SelectedValue.ToString());
            await RefreshWinservices();
            await RefreshWinservicesJobs();
            Loading.CloseLoading();
        }

        private async void 重启服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Loading.ShowLoading();
            await RestartService(lsbWinservices.SelectedValue.ToString());
            await RefreshWinservices();
            await RefreshWinservicesJobs();
            Loading.CloseLoading();
        }

        private async void 删除并卸载服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Loading.ShowLoading();
            await RemoveService(lsbWinservices.SelectedValue.ToString());
            await SaveWinservice();
            await RefreshWinservices();
            await RefreshWinservicesJobs();

            Loading.CloseLoading();
        }

        private void lsbWinservices_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                int currentIndex = e.Y / 12;
                if (currentIndex > lsbWinservices.Items.Count - 1)
                    return;
                if (lsbWinservices.SelectedItem != null && currentIndex != lsbWinservices.SelectedIndex)
                {
                    this.lsbWinservices.SetSelected(lsbWinservices.SelectedIndex, false);
                }

                this.lsbWinservices.SetSelected(currentIndex, true);
            }
        }

        private void lsbWinservices_DataSourceChanged(object sender, EventArgs e)
        {
            if (selectedServiceName != null && lsbWinservices.Items.Count > 0)
            {
                for (int i = 0; i < lsbWinservices.Items.Count; i++)
                {
                    dynamic item = lsbWinservices.Items[i];
                    if (item.ServiceName == selectedServiceName)
                    {
                        this.lsbWinservices.SetSelected(i, true);
                        return;
                    }
                }
            }
        }

        private void dgvWinserviceJobs_SelectionChanged(object sender, EventArgs e)
        {
            dgvWinserviceJobs.ClearSelection();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            new AddWinservice(this).ShowDialog();
        }

        private async void button4_Click(object sender, EventArgs e)
        {
            await RefreshWinservices(true);
            await RefreshWinservicesJobs();
        }

        #endregion

        #endregion

        /// <summary>
        /// 保存一个任务配置
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public async Task SaveJobConfiguration(JobConfiguration config)
        {
            Configs.AddOrUpdate(config.JobKey, config, (key, value) =>
            {
                return config;
            });

            await JsonHelper.SerializeToFileAsync(config, Path.Combine(JobConfiguationManager.ConfigFolderPath, config.JobKey + ".json"));
        }

        private async void MainForm_Load(object sender, EventArgs e)
        {
            await RefreshReflectionJobs();
            await RefreshWinservices();

            lsbWinservices.ValueMember = "ServiceName";
            lsbWinservices.DisplayMember = "Text";
            await RefreshWinservicesJobs();
        }

        private void ShowDes(Point location, ReflectionJob job)
        {
            new ShowJobDes(location, job).Show();
        }
        private void ShowDes(Point location, WinServices job)
        {
            new ShowJobDes(location, job).Show();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.ShowInTaskbar = false;
            this.WindowState = FormWindowState.Minimized;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.ShowInTaskbar = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void 退出系统ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}
